package jksys

import (
	"jkgo/jk/jklog"
	"jkgo/jk/jkprotocol"
	"jkgo/jk/jksys"
	cbase "findService/ss/servicebase"
	"time"

	l4g "github.com/alecthomas/log4go"
	"golanger.com/log"
)

const (
	service_selfname = "jksys"
)

type SysClient struct {
	cbase.ClientBase
	SysInfo *jksys.KFSystemInfo

	iotclient *cbase.SSIoTClient
}

func NewSysClient(addr string, port int, nettype int) (*SysClient, error) {
	l4g.Debug("New service sys client [%s:%d] \n", addr, port)
	sys := &SysClient{}
	err := sys.New(addr, port, nettype)
	if err != nil {
		return nil, err
	}

	err = sys.Dial()
	if err != nil {
		return nil, err
	}
	sys.SysInfo = jksys.NewSystemInfo()
	sys.Register()

	return sys, nil
}

func (sc *SysClient) Register() {
	str, _ := jkprotocol.JKProtoV6MakeRegister("jksys", sc.SysInfo)
	log.Debug("Register send %s", str)
	sc.Send(str)
}

func (sc *SysClient) Keepalive(interval time.Duration) {
	sc.KeepaliveCycle(interval, "jksys")
}

func (sc *SysClient) DealResponse(msg string) {
	p, err := jkprotocol.JKProtoV6Parse(msg)
	if err == nil {
		if p.H.R {
			s, _ := p.JKProtoV6MakeTR(service_selfname, false, p.B)
			n := sc.Send(s)
			jklog.L().Infoln("jksys response send out ", n)
		}
	} else {
		jklog.L().Errorln("jksys deal response parse err ", err)
	}
}

func (sc *SysClient) DealRecv() {
	jklog.L().Infoln("Start to deal recv of jksys")
	for {
		d, err := sc.RecvClient()
		if err != nil {
			jklog.L().Errorln("Recv client fail ", err)
			sc.SetDisconnected()
			time.Sleep(time.Second * 1)
			continue
		}
		jklog.L().Debugf("Recv data %s\n", string(d))
		sc.DealResponse(string(d))
	}
}
